local duangu = fk.CreateSkill {
  name = "hanqing__duangu",
}

Fk:loadTranslationTable{
  ["hanqing__duangu"] = "锻骨",
  [":hanqing__duangu"] = "出牌阶段限两次，你可以重铸任意角色的一张牌，若此牌为：<br>"..
  "火属性牌或装备牌，则令牌堆<a href=':hanqing__burst'>“爆发”</a>，然后该角色可使用此次一张亮出装备牌；<br>"..
  "手牌中的【杀】，则可置入任意角色的装备栏（一张伤害牌结算结束后，你可以将目标装备区的一张【杀】对使用者使用）。",

  ["#hanqing__duangu"] = "锻骨：重铸一名角色的一张牌",
  ["#hanqing__duangu-use"] = "锻骨：你可以使用其中一张装备牌",
  ["#hanqing__duangu-choose"] = "锻骨：你可以将%arg置入一名角色的装备栏",
  ["#hanqing__duangu-slash1"] = "锻骨：你可以将 %src 装备区的一张【杀】对 %dest 使用",
  ["#hanqing__duangu-slash2"] = "锻骨：你可以将目标角色装备区的一张【杀】对 %dest 使用",
}

local U = require "packages/hanqing/util"

duangu:addEffect("active", {
  anim_type = "control",
  prompt = "#hanqing__duangu",
  times = function(self, player)
    return player.phase == Player.Play and 2 - player:usedSkillTimes(duangu.name, Player.HistoryPhase) or -1
  end,
  card_num = 0,
  target_num = 1,
  can_use = function(self, player)
    return player:usedSkillTimes(duangu.name, Player.HistoryPhase) < 2
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, player, to_select, selected)
    return #selected == 0 and not to_select:isNude()
  end,
  on_use = function(self, room, effect)
    local player = effect.from
    local target = effect.tos[1]
    local id = room:askToChooseCard(player, {
      target = target,
      flag = "he",
      skill_name = duangu.name,
    })
    local card = Fk:getCardById(id)
    local yes1 = (card.type == Card.TypeEquip and table.contains(target:getCardIds("h"), id) or
      Fk:getCardById(id, true).type == Card.TypeEquip) or
      (card.is_damage_card and table.contains({"fire__slash", "fire_attack", "burning_camps"}, card.name))
    local yes2 = card.trueName == "slash" and table.contains(target:getCardIds("h"), id)
    room:recastCard({id}, target, duangu.name)
    if player.dead then return end
    if yes1 then
      local cards = U.burst(player)
      if not target.dead then
        cards = table.filter(cards, function (c)
          card = Fk:getCardById(c)
          return card.type == Card.TypeEquip and table.contains(room.discard_pile, c) and target:canUse(card)
        end)
        if #cards > 0 then
          room:askToUseRealCard(player, {
            pattern = cards,
            skill_name = duangu.name,
            prompt = "#hanqing__duangu-use",
            extra_data = {
              expand_pile = cards,
            }
          })
        end
      end
      if player.dead then return end
    end
    card = Fk:getCardById(id)
    if yes2 and Fk:getCardById(id).trueName == "slash" and table.contains(room.discard_pile, id) then
      local targets = table.filter(room.alive_players, function (p)
        return p:hasEmptyEquipSlot()
      end)
      if #targets > 0 then
        local success, dat = room:askToUseActiveSkill(player, {
          skill_name = "#hanqing__duangu_active",
          prompt = "#hanqing__duangu-choose:::"..Fk:getCardById(id):toLogString(),
        })
        if success and dat then
          local to = dat.targets[1]
          local choice = dat.interaction
          local mapper = {
            [Player.WeaponSlot] = "weapon",
            [Player.ArmorSlot] = "armor",
            [Player.OffensiveRideSlot] = "offensive_horse",
            [Player.DefensiveRideSlot] = "defensive_horse",
            [Player.TreasureSlot] = "treasure",
          }
          room:setCardMark(card, duangu.name, mapper[choice])
          room:filterCard(id, player)
          room:moveCardTo(card, Card.PlayerEquip, to, fk.ReasonPut, duangu.name, nil, true, player)
        end
      end
    end
  end,
})

duangu:addEffect(fk.AfterCardsMove, {
  can_refresh = function(self, event, target, player, data)
    for _, move in ipairs(data) do
      if move.toArea ~= Card.PlayerEquip and move.toArea ~= Card.Processing then
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerEquip and Fk:getCardById(info.cardId, true):getMark(duangu.name) ~= 0 then
            return true
          end
        end
      end
    end
  end,
  on_refresh = function(self, event, target, player, data)
    for _, move in ipairs(data) do
      if move.toArea ~= Card.PlayerEquip and move.toArea ~= Card.Processing then
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerEquip then
            player.room:setCardMark(Fk:getCardById(info.cardId, true), duangu.name, 0)
          end
        end
      end
    end
  end,
})

duangu:addEffect("filter", {
  card_filter = function(self, to_select, player, isJudgeEvent)
    return to_select:getMark(duangu.name) ~= 0
  end,
  view_as = function(self, player, to_select)
    return Fk:cloneCard(to_select:getMark(duangu.name).."__hanqing__duangu", to_select.suit, to_select.number)
  end,
})

duangu:addEffect(fk.CardUseFinished, {
  anim_type = "offensive",
  can_trigger = function (self, event, target, player, data)
    return target ~= player and player:hasSkill(duangu.name) and
      data.card.is_damage_card and not target.dead and
      table.find(data.tos, function (p)
        return not p.dead and
          table.find(p:getCardIds("e"), function (id)
            return Fk:getCardById(id, true).trueName == "slash" and
              player:canUseTo(Fk:getCardById(id, true), target, { bypass_distances = true, bypass_times = true })
          end) ~= nil
      end)
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local targets = table.filter(data.tos, function (p)
      return not p.dead and
        table.find(p:getCardIds("e"), function (id)
          return Fk:getCardById(id, true).trueName == "slash" and
            player:canUseTo(Fk:getCardById(id, true), target, { bypass_distances = true, bypass_times = true })
        end) ~= nil
    end)
    if #targets > 1 then
      local to = room:askToChoosePlayers(player, {
        min_num = 1,
        max_num = 1,
        targets = targets,
        skill_name = duangu.name,
        prompt = "#hanqing__duangu-slash2::"..target.id,
        cancelable = true,
      })
      if #to > 0 then
        event:setCostData(self, {extra_data = to[1]})
        return true
      end
    else
      if room:askToSkillInvoke(player, {
        skill_name = duangu.name,
        prompt = "#hanqing__duangu-slash1:"..targets[1].id..":"..target.id,
      }) then
        event:setCostData(self, {extra_data = targets[1]})
        return true
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local to = event:getCostData(self).extra_data
    local cards = table.filter(to:getCardIds("e"), function (id)
      return Fk:getCardById(id, true).trueName == "slash" and
        player:canUseTo(Fk:getCardById(id, true), target, { bypass_distances = true, bypass_times = true })
    end)
    if #cards > 1 then
      cards = room:askToChooseCard(player, {
        target = to,
        flag = { card_data = {{ to.general, cards }} },
        skill_name = duangu.name,
      })
      cards = {cards}
    end
    room:useVirtualCard(Fk:getCardById(cards[1], true).name, cards, player, target, duangu.name, true)
  end,
})

return duangu
